from flask import Blueprint, request, jsonify
from app import db, jwt
from app.models.body_composition import BodyComposition
from flask_jwt_extended import jwt_required, get_jwt_identity

bp = Blueprint('body_composition', __name__, url_prefix='/api/body-composition')

@bp.route('', methods=['POST'])
@jwt_required()
def create_body_composition():
    """创建身体成分记录"""
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # 计算BMI
        height = data.get('height')
        weight = data.get('weight')
        bmi = None
        if height and weight and height > 0:
            bmi = round(weight / ((height / 100) ** 2), 2)
        
        body_composition = BodyComposition(
            user_id=user_id,
            weight=data.get('weight'),
            bmi=bmi,
            body_fat_percentage=data.get('body_fat_percentage'),
            muscle_mass=data.get('muscle_mass'),
            water_percentage=data.get('water_percentage'),
            waist_circumference=data.get('waist_circumference'),
            hip_circumference=data.get('hip_circumference')
        )
        
        db.session.add(body_composition)
        db.session.commit()
        
        return jsonify({
            'message': '身体成分记录创建成功',
            'data': body_composition.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('', methods=['GET'])
@jwt_required()
def get_body_compositions():
    """获取用户的全部身体成分记录"""
    try:
        user_id = get_jwt_identity()
        records = BodyComposition.query.filter_by(user_id=user_id).order_by(BodyComposition.record_date.desc()).all()
        
        return jsonify({
            'data': [record.to_dict() for record in records]
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['GET'])
@jwt_required()
def get_body_composition_by_id(record_id):
    """获取特定身体成分记录"""
    try:
        user_id = get_jwt_identity()
        record = BodyComposition.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
            
        return jsonify({
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['PUT'])
@jwt_required()
def update_body_composition(record_id):
    """更新身体成分记录"""
    try:
        user_id = get_jwt_identity()
        record = BodyComposition.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        data = request.get_json()
        
        # 更新字段
        update_fields = [
            'weight', 'body_fat_percentage', 'muscle_mass', 
            'water_percentage', 'waist_circumference', 'hip_circumference'
        ]
        
        for field in update_fields:
            if field in data:
                setattr(record, field, data[field])
        
        # 重新计算BMI
        if 'weight' in data or 'height' in data:
            user = record.user
            if user.height and record.weight and user.height > 0:
                record.bmi = round(record.weight / ((user.height / 100) ** 2), 2)
        
        db.session.commit()
        
        return jsonify({
            'message': '身体成分记录更新成功',
            'data': record.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@bp.route('/<int:record_id>', methods=['DELETE'])
@jwt_required()
def delete_body_composition(record_id):
    """删除身体成分记录"""
    try:
        user_id = get_jwt_identity()
        record = BodyComposition.query.filter_by(id=record_id, user_id=user_id).first()
        
        if not record:
            return jsonify({'error': '记录不存在'}), 404
        
        db.session.delete(record)
        db.session.commit()
        
        return jsonify({
            'message': '身体成分记录删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500